package cn._2dland.gae.httpclient;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class Cookie {
	public String name;
	public String value;
	public String domain;
	public String path;
	public long expires;

	private static DateFormat dataFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);

	/** 解析Cookie串，返回一个Cookie对象 */
	public static Cookie parse(String cookieStr) {
		if(cookieStr == null) return null;
		// 拆分字符串
		String fields[] = cookieStr.split("; ");
		if(fields == null || fields.length == 0)
			return null;
		// 第一个字段为cookie值
		Cookie c = new Cookie();
		c.name = fields[0].substring(0, fields[0].indexOf("="));
		c.value = fields[0].substring(fields[0].indexOf("=") + 1);
		// 其他字段为cookie属性
		Map<String, String> attrs = new HashMap<String, String>();
		for(int i=1; i<fields.length; i++) {
			String k = fields[i].substring(0, fields[i].indexOf("=")).toLowerCase();
			String v = fields[i].substring(fields[i].indexOf("=") + 1).toLowerCase();
			attrs.put(k, v);
		}
		c.expires = parseGMT(attrs.get("expires"));
		c.domain = attrs.get("domain");
		c.path = attrs.get("path")==null ? "/" : attrs.get("path");
		return c;
	}

	/** 解析GMT时间串 */
	private static long parseGMT(String GMTStr) {
		long time = 0;
		try { time = dataFormat.parse(GMTStr).getTime(); }
		catch (Exception e) { time = 0; }
		return time;
	}
}
